/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.interceptor;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiOptimisticLockingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Intercepts {@link com.je.bpm.engine.ActivitiOptimisticLockingException} and tries to run the same command again. The number of retries and the time waited between retries is configurable.
 * 乐观锁重试拦截器，用于在命令执行失败，重试（重新执行指令）的次数
 */
public class RetryInterceptor extends AbstractCommandInterceptor {

    private static Logger log = LoggerFactory.getLogger(RetryInterceptor.class);

    protected int numOfRetries = 3;
    protected int waitTimeInMs = 50;
    protected int waitIncreaseFactor = 5;
    
    @Override
    public <T> T execute(CommandConfig config, Command<T> command) {
        long waitTime = waitTimeInMs;
        int failedAttempts = 0;

        do {
            if (failedAttempts > 0) {
                log.info("Waiting for {}ms before retrying the command.", waitTime);
                waitBeforeRetry(waitTime);
                waitTime *= waitIncreaseFactor;
            }

            try {

                // try to execute the command
                return next.execute(config, command);

            } catch (ActivitiOptimisticLockingException e) {
                log.info("Caught optimistic locking exception: " + e);
            }

            failedAttempts++;
        } while (failedAttempts <= numOfRetries);

        throw new ActivitiException(numOfRetries + " retries failed with ActivitiOptimisticLockingException. Giving up.");
    }

    protected void waitBeforeRetry(long waitTime) {
        try {
            Thread.sleep(waitTime);
        } catch (InterruptedException e) {
            log.debug("I am interrupted while waiting for a retry.");
        }
    }

    public void setNumOfRetries(int numOfRetries) {
        this.numOfRetries = numOfRetries;
    }

    public void setWaitIncreaseFactor(int waitIncreaseFactor) {
        this.waitIncreaseFactor = waitIncreaseFactor;
    }

    public void setWaitTimeInMs(int waitTimeInMs) {
        this.waitTimeInMs = waitTimeInMs;
    }

    public int getNumOfRetries() {
        return numOfRetries;
    }

    public int getWaitIncreaseFactor() {
        return waitIncreaseFactor;
    }

    public int getWaitTimeInMs() {
        return waitTimeInMs;
    }
}
